#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Copyright (C) 2025 Huawei Technologies Co., Ltd. All rights reserved.

import os
import subprocess
import sys
import time
import shutil
import logging

from openubmc_ansible.utils import BMC_EXCU_PATH

logging.basicConfig(format="%(message)s")
logging.error('Start installing openUBMC ansible module')

if __name__ == "__main__":
    try:
        import ansible
        from ansible.module_utils.six.moves import input as ansible_input
    except ImportError as e:
        logging.error("Ansible is not installed.")
        sys.exit(1)

    try:
        import requests
    except ImportError as e:
        logging.warning("You must install the python requests module. Otherwise, the openUBMC cannot be connected!")

    ansible_installed_path = ansible.__path__[0]

    openubmc_lib_path = os.path.join(ansible_installed_path, "modules")

    if os.path.exists(os.path.join(openubmc_lib_path, 'openubmc')):
        logging.error("The openubmc_ansible module already exists, Do you want to upgrade it? (y/n)")
        choice = ansible_input()
        if choice in ['y', 'Y']:
            ret = subprocess.call(["/usr/bin/cp", "-r", "./openubmc_ansible/openubmc", openubmc_lib_path], shell=False)
            if ret != 0:
                logging.error("Failed to copy openubmc module!")
                sys.exit(1)
        else:
            logging.error("Cancel installation openubmc_ansible module!")
            sys.exit(1)
    else:
        ret = subprocess.call(["/usr/bin/cp", "-r", "./openubmc_ansible/openubmc", openubmc_lib_path], shell=False)
        if ret != 0:
            logging.error("Failed to copy openubmc_ansible/openubmc module!")
            sys.exit(1)

    openubmc_utils_path = os.path.join(os.path.dirname(ansible_installed_path), "openubmc_ansible")
    date_str = time.strftime("%Y%m%d%H%M%S", time.localtime())
    yml_bak = ("%s_%s") % (BMC_EXCU_PATH, date_str)
    if os.path.exists(BMC_EXCU_PATH):
        logging.error("Backup the %s to %s" % (BMC_EXCU_PATH, yml_bak))
        ret = subprocess.call(["/usr/bin/cp", "-r", BMC_EXCU_PATH, yml_bak], shell=False)
        if ret != 0:
            logging.error("Failed to backup the %s to %s!" % (BMC_EXCU_PATH, yml_bak))
    else:
        ret = subprocess.call(["mkdir", "-p", BMC_EXCU_PATH], shell=False)
        if ret != 0:
            logging.error("Failed to mkdir %s" % BMC_EXCU_PATH)
            logging.error("Installation failed!")
            sys.exit(1)

    ret = subprocess.call(["/usr/bin/cp", "-r", "./examples", BMC_EXCU_PATH], shell=False)
    if ret != 0:
        logging.error("Failed to copy yml to %s" % BMC_EXCU_PATH)

    ret = subprocess.call(["/usr/bin/cp", "./ssl.cfg", BMC_EXCU_PATH], shell=False)
    if ret != 0:
        logging.error("Failed to copy ssl.cfg to %s" % BMC_EXCU_PATH)

    if not os.path.exists(openubmc_utils_path):
        ret = subprocess.call(["mkdir", "-p", openubmc_utils_path], shell=False)
        if ret != 0:
            logging.error("Failed to mkdir %s" % openubmc_utils_path)
            logging.error("Installation failed!")
            sys.exit(1)

    flag = False
    for file_name in os.listdir('./openubmc_ansible/'):
        if file_name.endswith(".py"):
            flag = True
            file_path = os.path.join('./openubmc_ansible/', file_name)
            shutil.copy(file_path, openubmc_utils_path)
    if not flag:
        logging.error("Failed to copy openubmc_ansible utile files")
        logging.error("Installation failed!")
        sys.exit(1)

    ret = subprocess.call(["/usr/bin/cp", "-rf", "./openubmc_ansible/openubmc_redfish_api", openubmc_utils_path],
                        shell=False)
    if ret != 0:
        logging.error("Failed to copy openubmc redfish api")
        logging.error("Installation failed!")
        sys.exit(1)

    logging.error('Installation openUBMC ansible module completed')
    sys.exit(0)
